package cn.fl.npspl.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.cmm.base.framework.logger.eum.LogOperEnum;
import cn.fl.system.service.ISysDictionaryService;
import fl.constant.facade.framework.constant.BusinessIdConstant;
import fl.spl.facade.framework.constant.SplSystemConstant;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.npspl.service.ISplNpSocialRlService;
import cn.fl.npspl.vo.SplNpSocialRlVO;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.spl.facade.npspl.condition.SplNpSocialRlQC;
import fl.spl.facade.spl.constant.SplInfoConstant;

/**
 * @Description: 自然人经销商社会关系表 控制层
 */
@Controller
@RequestMapping("/npspl/splnpsocialrl")
public class SplNpSocialRlController extends BaseController {

    /**
     * SplNpSocialRl 服务层BEAN
     */
    @Autowired
    private ISplNpSocialRlService splNpSocialRlService;
    @Autowired
    private ISysDictionaryService sysDictionaryService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView view = new ModelAndView("npspl/splNpSocialRl/splNpSocialRlList");

        return view;
    }

    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView view = new ModelAndView("npspl/splNpSocialRl/splNpSocialRlAdd");
        
        return view;
    }
    
    /**
     * 到新增修改页面
     */
    @RequestMapping(value = "/toAddNpSocialRlPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddNpSocialRlPage(HttpServletRequest request, HttpServletResponse response) {

        ModelAndView view = new ModelAndView("npspl/splNpSocialRl/npSocialRlAdd");
        
        List<KeyValueVO> certTypCdList = this.splNpSocialRlService.searchCertTypCdList();
        List<KeyValueVO> rlTypCdList = this.splNpSocialRlService.searchRlTypCdList(DictionaryConstant.CODE_GRP_RL_TYP_CD);
        
        view.addObject("rlTypCDListJSON", JSONObject.toJSON(rlTypCdList));
        view.addObject("certTypCdListJSON", JSONObject.toJSON(certTypCdList));

        return view;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("npspl/splNpSocialRl/splNpSocialRlModify");
        view.addObject("id", id);
        return view;
    }

    /**
     * 到详情页面
     */
    @RequestMapping(value = "/toDetailPage.do", method = {RequestMethod.GET})
    public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {

        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("npspl/splNpSocialRl/splNpSocialRlDetail");
        view.addObject("id", id);

        return view;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String splId = request.getParameter("splId");

        String isEncrypt = request.getParameter("isEncrypt");

        ListPageVO<SplNpSocialRlVO> listPage=null;

		if(StringUtils.isEmpty(splId)){
			//新能源事业部 联系人不必填
			if(PropertiesCacheUtils.getProperty(SystemConstant.FL_BUS_XNY_ORG_CD).equals(CurrentThreadContext.getCurrentBuOrgCd())){
				listPage = new ListPageVO<SplNpSocialRlVO>(new ArrayList<SplNpSocialRlVO>(), 0);
			}else{
				listPage = new ListPageVO<SplNpSocialRlVO>(this.setSplNpSocialRlList(null), 0);
			}
			return listPage;
		}else {
			Pager page = new Pager();
			if (StringUtils.isNotEmpty(currentPage)) {
				page.setCurrentPage(Integer.parseInt(currentPage));
			}

			if (StringUtils.isNotEmpty(currentPage)) {
				page.setEveryPage(Integer.parseInt(pageSize));
			}

			SplNpSocialRlQC qc = new SplNpSocialRlQC();
			qc.setCstId(Long.valueOf(splId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
			page.setCondition(qc);
			//page.setEveryPage(Integer.MAX_VALUE);//最大数据量

            Pager pager;
            if (StringUtils.isNotEmpty(isEncrypt) && BaseConstant.IS_YESNO_YES_STR.equals(isEncrypt)) {
                String roleisEncrypt = this.sysDictionaryService.getRoleisEncrypt();
                if (BaseConstant.IS_YESNO_YES_STR.equals(roleisEncrypt)) {
                    pager = this.splNpSocialRlService.searchWithEncryptListPage(page);
                } else {
                    pager = this.splNpSocialRlService.searchListPage(page);
                }
            } else {
                pager = this.splNpSocialRlService.searchListPage(page);
            }
            List<SplNpSocialRlVO> list = (List<SplNpSocialRlVO>) pager.getResultList();
			if(PropertiesCacheUtils.getProperty(SystemConstant.FL_BUS_XNY_ORG_CD).equals(CurrentThreadContext.getCurrentBuOrgCd())){
				//新能源事业部 - 无必输联系人
			}else{
				//将未存在的必输联系人添加
				list=this.setSplNpSocialRlList(list);
			}
			listPage = new ListPageVO<SplNpSocialRlVO>(list, pager.getTotalCount());
            BaseLogUtils.newWebLogger("获取供应商列表页面数据.DATA:"+JSONObject.toJSONString(listPage)).setLogOperType(LogOperEnum.RESP)
                    .setSysCd(CurrentThreadContext.getCurrentSysCd())
                    .setChannelCd(SplSystemConstant.FL_WEB_CHL_CD)
                    .setBussinessId(BusinessIdConstant.LOG_SPL_MANAGER_CD)
                    .setWarning(false)
                    .info();
		}
		return listPage;
	}

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "新增成功!");
        SplNpSocialRlVO entity = null;
        try {
            entity = new SplNpSocialRlVO();
            //TODO ADD PARAM
            Long id = this.splNpSocialRlService.add(entity);
            result.setData(id);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "修改成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("数据不存在!");
            return result;
        }
        SplNpSocialRlVO entity = null;
        try {
            entity = new SplNpSocialRlVO();
            entity.setId(Long.valueOf(id));
            //entity.setName(name);
            //TODO ADD PARAM
            boolean success = this.splNpSocialRlService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("修改失败!");
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }

        return result;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "删除成功!");
        if (StringUtils.isEmpty(id) && StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }
        try {
            if(StringUtils.isNotEmpty(id)) {
                this.splNpSocialRlService.removeById(Long.valueOf(id));
            }else{
                JSONArray idsArray = JSONArray.fromObject(ids);
                for (Object object : idsArray) {
                    this.splNpSocialRlService.removeById(Long.valueOf(object.toString()));
                }

            }

        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {

        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "操作成功!");
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("主键不能为空!");
            return result;
        }

        try {
            SplNpSocialRlVO vo = this.splNpSocialRlService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("数据不存在!");
            }
            result.setData(vo);
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("系统错误,请联系管理员!");
        }

        return result;
    }
    
    /**
	 * 封装必输联系人信息
	 * @param voList
	 */
	private List<SplNpSocialRlVO> setSplNpSocialRlList(List<SplNpSocialRlVO> voList){
		//证件类型
		List<KeyValueVO> certTypCdList = this.splNpSocialRlService.searchCertTypCdList();
		Map<String, KeyValueVO> certTypCdMap = new HashMap<String, KeyValueVO>();
		for (KeyValueVO keyValueVO : certTypCdList) {
			certTypCdMap.put(keyValueVO.getKey(), keyValueVO);
		}
		
		//获取默认证件类型名称
		String defCodNm = "";
		for (KeyValueVO keyValueVO : certTypCdList) {
			if(keyValueVO.getKey().equals(SplInfoConstant.CODE_CERT_TYP_DEF_CD)){
				defCodNm = keyValueVO.getValue();
			}
		}
		//联系人类型
		List<KeyValueVO> rlTypCDList = this.splNpSocialRlService.searchRlTypCdList(DictionaryConstant.CODE_GRP_RL_TYP_CD);
		Map<String, KeyValueVO> rlTypCdMap = new HashMap<String, KeyValueVO>();
		for (KeyValueVO keyValueVO : rlTypCDList) {
			rlTypCdMap.put(keyValueVO.getKey(), keyValueVO);
		}
		
		Map<String,SplNpSocialRlVO> map=new HashMap<String,SplNpSocialRlVO>();
		//查询出所有必输联系人信息
		if(null != rlTypCDList && rlTypCDList.size()>0) {
			for (KeyValueVO keyValueVO : rlTypCDList) {
				if(keyValueVO.getKey().equals("10")) {
					SplNpSocialRlVO vo = new SplNpSocialRlVO();
					vo.setRlTypCd(keyValueVO.getKey());
					vo.setRlTypCdNm(keyValueVO.getValue());
					vo.setCertTypCd(SplInfoConstant.CODE_CERT_TYP_DEF_CD);
					vo.setCertTypCdNm(defCodNm);
					vo.setIsDel(BaseConstant.IS_YESNO_NO);
					vo.setIsDefault(BaseConstant.IS_YESNO_YES);
					map.put(keyValueVO.getKey(), vo);
				}
			}
		}
		//判断修改的联系人信息中是否存在必输的联系人
		if(null != voList && voList.size()>0){
			//循环将已经存在的vo信息
			for (SplNpSocialRlVO splRlPsnVO : voList) {
				//如果存在必输联系人，将必输Map中联系人去除
				if(map.containsKey(splRlPsnVO.getRlTypCd())){
					map.remove(splRlPsnVO.getRlTypCd());
				}
			}
		}else{//新增时或修改时无联系人信息，创建联系人
			voList=new ArrayList<SplNpSocialRlVO>();
		}
		//将去除重复后的必输联系人添加到联系人列表中
		if(null != map && map.size()>0){
			for (Map.Entry<String, SplNpSocialRlVO> entry : map.entrySet()) {
				voList.add(entry.getValue());
			}
		}
		
		for (SplNpSocialRlVO vo : voList) {
			if (StringUtils.isNotEmpty(vo.getCertTypCd()) && certTypCdMap.containsKey(vo.getCertTypCd())) {
				vo.setCertTypCdNm(certTypCdMap.get(vo.getCertTypCd()).getValue());
			}
			if (StringUtils.isNotEmpty(vo.getRlTypCd()) && rlTypCdMap.containsKey(vo.getRlTypCd())) {
				vo.setRlTypCdNm(rlTypCdMap.get(vo.getRlTypCd()).getValue());
			}
		}
		
		return voList;
	}
}

